import { Location } from '@nutui/icons-react-taro'
import { Address, Cell } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import { useEffect, useMemo, useState } from 'react'
import { useNavigation } from '../../hooks/useNavigation'
import './index.less'

interface AddressList {
  id?: string | number
  name?: string
  phone?: string
  isDefault?: boolean
  provinceName: string
  cityName: string
  countyName: string
  townName: string
  addressDetail: string
  selectedAddress?: boolean
}

interface AddressSelectProps {
  onChange?: (data: string | number) => void
  value?: string | number
  options: AddressList[]
}

const AddressSelect = ({ onChange, value, options }: AddressSelectProps) => {
  const [text, setText] = useState('请选择地址')
  const [name, setName] = useState('')
  const [phone, setPhone] = useState('')
  const [visible, setVisible] = useState(false)
  const { navigateTo } = useNavigation()

  const existList = useMemo(() => {
    return options.map((item) => ({
      ...item,
      selectedAddress: item.id === value,
    }))
  }, [options, value])

  useEffect(() => {
    const _v = options.find((item) => item.id === value)
    if (_v) {
      setText(_v.provinceName + _v.cityName + _v.countyName + _v.townName + _v.addressDetail)
      setName(_v?.name || '')
      setPhone(_v?.phone || '')
    }
  }, [options, value])

  const selectedTwo = (data: AddressList) => {
    onChange && onChange(data.id || '')
  }

  return (
    <>
      <Cell
        title={
          <View className='cell-content'>
            <Location />
            {existList.length > 0 ? (
              <View className='cell-content-text'>
                <Text>{name}</Text>
                <Text>{phone}</Text>
                <Text>{text}</Text>
              </View>
            ) : (
              <Text>暂无地址信息，请先添加地址</Text>
            )}
          </View>
        }
        onClick={() => {
          existList.length > 0 ? setVisible(true) : navigateTo('/pages/address-management/index')
        }}
      />
      <Address
        visible={visible}
        type='exist'
        existList={existList}
        onExistSelect={selectedTwo}
        title='地址选择'
        onClose={() => setVisible(false)}
      />
    </>
  )
}
export default AddressSelect
